package com.ly.mpayment.rest.up.qingchi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.HttpClient;
import com.ly.mpayment.core.util.StringSort;
import com.ly.mpayment.core.util.StringUtils;
import com.ly.mpayment.persist.entity.BusinessType;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.entity.UpShopProduct;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.mortbay.util.MultiMap;
import org.mortbay.util.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.net.URLDecoder;
import java.util.*;

@Component
@Path("qingchi")
public class QingChiRest {

    /**
     * 提单错误直接失败
     * 1	通用错误码
     * 100	参数错误
     * 101	method错误
     * 102	sign错误
     * 104	时间戳格式错误
     * 105	timestamp时间误差超过10分钟
     * 202	商家余额不足
     * 203	商家不存在
     * 204	商家被禁用
     * 401	IP访问受限
     * 403	权限不足
     * 701	当前接口限流，请稍后再试
     * 702	当前接口暂时不可用，请稍后再试
     * 703	调用过于频繁，请调整调用频率
     * 1101	外部订单号重复
     * 1303	商品不存在
     * 1304	商品已下架
     * 1401	库存不足
     */
    private static Set<String> codesError = new HashSet<String>(){{
        add("1");
        add("100");
        add("101");
        add("102");
        add("104");
        add("105");
        add("202");
        add("203");
        add("204");
        add("403");
        add("401");
        add("701");
        add("702");
        add("703");
        add("1101");
        add("1303");
        add("1304");
        add("1401");
    }};
    Logger logger = Logger.getLogger(QingChiRest.class);
    @Autowired
    IUporderService upOrderService;
    @Autowired
    IDownRechargeFlowService flowService;
    @Autowired
    IDownShopInfoService shopService;
    @Autowired
    IUpShopInfoService upShopInfoService;

    public static void main(String[] args) {
        charge_params();
        //new QingChiRest().commitOrder(new UpOrder(){{
        //    setUpphonenum("18398768087");
        //    setCreatetime(new Date());
        //    setAreaName("经典区-飞龙");
        //    setServer("");
        //    setSourceIp("");
        //    setName("完美世界经典服");
        //    setUprechargenum(10);
        //    setRechargeType("完美一卡通");
        //    setUpShopPro(new UpShopProduct(){{
        //        setProductCode("1000");
        //        setBusinessType(new BusinessType(){{
        //        	setBusCode("XX");
        //	 }});
        //    }});
        //    setUporderuuid("5555");
        //}},new UpShopInfo(){{
        //    setOrderCommitAddress("http://qcwl.youyuwang.cn/api/gateway");
        //    setAppId("1000");
        //    setUpkey("7e710fbc33efb95a5089bfbf5f0408edc83bef84b01d7d7771c6cd6e1366ff40");
        //    setUpshopip("7e710fbc33efb95a5089bfbf5f0408edc83bef84b01d7d7771c6cd6e1366ff40");
        //    setOrderCallAddress("http://120.79.142.7:8181/mpayment/client/qingchi/callBack");
        //}});
    }

    public static void charge_params() {
        JSONObject data = new JSONObject();
        data.put("method","esales.product.charge_params");
        data.put("customer_id","1000");
        data.put("timestamp",System.currentTimeMillis() / 1000+"");
        data.put("product_id","1001");
        data.put("sign",MD5.md5("7e710fbc33efb95a5089bfbf5f0408edc83bef84b01d7d7771c6cd6e1366ff40"+StringSort.doSignKeyValue(data)));
        String res = HttpClient.post("http://qcwl.youyuwang.cn/api/gateway",data.toString());
    }

    /**
     * @return
     */
    @Path("callBack")
    @POST
    public synchronized String callBack(@RequestBody String body){
        logger.info("qingchi_back:"+body);
        if(!StringUtils.isBlank(body)){
            MultiMap item = Util.parceString(body);
            UpOrder order = upOrderService.findById(item.getString("out_order_id"));
            if (order != null && item.getString("status").equals("200") && order.getStatus() == Config.status[0]) {
                order.setRemark(URLDecoder.decode(item.getString("status_info")));
                RechargeRest.successUpOrder.add(order);
                return "ok";
            }else if(order != null && order.getStatus() == Config.status[0] && item.getString("status").equals("500")){
                order.setRemark(URLDecoder.decode(item.getString("status_info")));
                RechargeRest.failtUpOrder.add(order);
                return "ok";
            }else{
                logger.info("qingchi_not_found_order:" + body +","+ (order == null ? " order is null" : order.getUpphonenum() ));
            }
        }
        return "ok";
    }

    /**
     * @return
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        if(upOrder != null ){
            UpOrder product = upOrderService.findOrderProduct(upOrder.getUporderuuid());
            if (product != null) {
                JSONObject data = new JSONObject();
                data.put("method","esales.order.get");
                data.put("customer_id",shopInfo.getAppId());
                data.put("timestamp",System.currentTimeMillis() / 1000+"");
                data.put("out_order_id",upOrder.getUporderuuid());

                data.put("sign",MD5.md5(shopInfo.getUpkey()+StringSort.doSignKeyValue(data)));
                String res = HttpClient.post(shopInfo.getOrderStatusAddress(),data.toString());
                logger.info("queryqingchi:"+res+"data:"+data+",phone:"+upOrder.getUpphonenum());
                if(res != null){

                    try {
                        JSONObject result = JSONObject.parseObject(res);
                        //订单状态（100：等待发货，200：交易成功，500：交易失败，300：可疑订单）
                        if(result.containsKey("code") && result.getString("code").equals("0")){
                            JSONObject orderJson = result.getJSONObject("data");
                            if(orderJson.getString("status").equals("200") ){
                                UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
                                if(order != null && order.getStatus() == Config.status[0]){
                                    order.setRemark("");
                                    RechargeRest.successUpOrder.add(order);
                                }
                            }else if( orderJson.getString("status").equals("500")){
                                UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
                                if( order != null && order.getStatus() == Config.status[0]){
                                    order.setRemark( orderJson.getString("message"));
                                    RechargeRest.failtUpOrder.add(order);
                                }
                            }
                        }else{
                            logger.debug("queryqingchi查询失败:"+upOrder.getUpphonenum());
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    logger.info("queryqingchi order failt:"+upOrder.getUpphonenum());
                }
            }
        }else{
            logger.info("queryqingchi order failt:"+upOrder.getUpphonenum());
        }
    }

    /**
     * @return
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        UpOrder product = order;//this.upOrderService.findOrderProduct(order.getUporderuuid());
        //卡密不提交
        if (product != null && !product.getUpShopPro().getBusinessType().getBusCode().equals("KM")) {
            JSONObject data = new JSONObject();
            data.put("method","esales.order.purchase");
            data.put("customer_id",shop.getAppId());
            data.put("timestamp",System.currentTimeMillis() / 1000+"");

            data.put("out_order_id",order.getUporderuuid());
            //购买数量
            data.put("quantity",order.getUprechargenum());
            //商品编号
            //String packages = product.getUpShopPro().getProductCode();
            data.put("product_id",product.getUpShopPro().getProductCode());
            //packages[1]
            data.put("notify_url", shop.getOrderCallAddress());

            JSONObject charge_params = new JSONObject();
            charge_params.put("charge_account",order.getUpphonenum());
            charge_params.put("game","");
            charge_params.put("game_name","");
            charge_params.put("area","");

            charge_params.put("charge_account_password","");

            //data.put("FaceValue",product.getUpShopPro().getUpfacevalue());

            if(!StringUtils.isBlank(order.getName())){
                //充值名称
                charge_params.put("game_name",order.getName());
            }

            //区域名称
            if(!StringUtils.isBlank(order.getAreaName())){
                charge_params.put("area_name",(order.getAreaName()));
            }

            //区域名称
            if(!StringUtils.isBlank(order.getSourceIp()) && !order.getSourceIp().contains(".")){
                data.put("end_customer_region",order.getSourceIp());
            }
            //客户端ip
            if(!StringUtils.isBlank(order.getSourceIp()) && order.getSourceIp().contains(".") ){
                data.put("end_customer_ip",order.getSourceIp().replace(" ",""));
            }
            //充值服务器
            if(!StringUtils.isBlank(order.getServer())){
                charge_params.put("server",order.getServer());
                //charge_params.put("server_name","");
            }
            //充值类型
            if(!StringUtils.isBlank(order.getRechargeType())){
                //charge_params.put("charge_account_type",order.getRechargeType());
                //charge_params.put("charge_account_type_name",order.getRechargeType());
                charge_params.put("charge_account_type","");
                charge_params.put("charge_account_type_name","");
                //charge_mode传value值，charge_mode_name传name值
                //{"name":"帐号直充","value":"1"},{"name":"点数寄售","value":"2"}]
                if(order.getRechargeType().equals("帐号直充")){
                    charge_params.put("charge_mode","1");
                    charge_params.put("charge_mode_name",order.getRechargeType());
                }else if(order.getRechargeType().equals("点数寄售")){
                    charge_params.put("charge_mode","2");
                    charge_params.put("charge_mode_name",order.getRechargeType());
                }

            }

            data.put("charge_params",charge_params.toString());

            data.put("sign",MD5.md5(shop.getUpkey()+StringSort.doSignKeyValue(data)));

            String res = HttpClient.postUrl(shop.getOrderCommitAddress(),StringSort.jsonToString(data));
            logger.info("commitqingchi_result:" + data +",phone:"+order.getUpphonenum()+",res:"+res);
            if (!StringUtils.isBlank(res)) {
                try {
                    JSONObject result = JSONObject.parseObject(res);
                    if(result.containsKey("code") && result.getString("code").equals("0")){
                        upOrderService.updateUpOrderMsg(order, (result != null &&
                                        result.containsKey("data")) ? result.getJSONObject("data").getString("order_id"): ""
                                ,result.getString("message"));
                    }else if (result.containsKey("code") && codesError.contains(result.getString("code"))) {
                        order.setRemark(result.containsKey("message") ?	result.getString("message") : Config.orderFailA);
                        RechargeRest.failtUpOrder.add(order);
                    }
                }catch (Exception p){
                    p.printStackTrace();
                }
            } else {
                upOrderService.updateUpOrderArtificial(order, "" , "人工");
                logger.info("commitqingchi_error" + order.getUpphonenum());
            }
        }
    }



}
